<template>
  <div
    :style="{ right: `${modalRight}px`, top: `${modalTop}px` }"
    @mousedown="mousedown($event)"
    @mouseup="mouseup($event)"
  >
    <div class="title-container">
      <span v-if="!finished">
        正在上传（{{ finishedNumber }}/{{ getProgresses.length }}）
      </span>
      <span v-else>
        任务结束
      </span>
      <div class="more-icon-container">
        <a-icon
          v-if="winOpen"
          type="minus"
          class="more-icon"
          @click="winOpen = false"
        />
        <a-icon
          v-else
          type="border"
          class="more-icon"
          @click="winOpen = true"
        />
        <a-icon
          type="close"
          :style="{
            'vertical-align': 'top',
            opacity: finished ? '1' : '0.3',
            cursor: finished ? 'pointer' : 'default',
          }"
          @click="closeProgressPage"
        />
      </div>
    </div>
    <div class="table-container" :style="{ height: winOpen ? '128px' : 0 }">
      <div v-show="winOpen" style="border-top: 1px solid #e9e9e9;">
        <div
          v-for="(item, index) in uploadProgresses.progresses"
          :key="index"
          class="table-item"
        >
          <div class="table-name">
            <!--表名-->
            <a-tooltip>
              <template slot="title">
                {{ item.table }}
              </template>
              {{ item.table }}
            </a-tooltip>
          </div>
          <!--导入出错-->
          <div v-if="item.status === '失败'" class="progress-container">
            <a-progress
              class="task-progress"
              size="small"
              :percent="item.progress / 100"
              status="exception"
              :show-info="false"
            />
            <a-icon-font class="icon-status" type="iconwuquanxian" />
            服务器错误
          </div>
          <!--导入成功-->
          <div v-else-if="item.status === '成功'" class="progress-container">
            <a-progress
              class="task-progress"
              size="small"
              :percent="item.progress / 100"
              :show-info="false"
            />
            <a-icon-font
              class="icon-status"
              type="iconyouquanxianlianjiechenggong"
            />
            已完成
            <a-button
              v-if="finished"
              size="small"
              type="link"
              :style="{ height: '12px', 'font-size': '12px' }"
              @click="clickTable(item.datasetId)"
            >
              查看
            </a-button>
          </div>
          <!--导入过程中-->
          <div v-else-if="item.status === '进行中'" class="progress-container">
            <a-progress
              class="task-progress"
              size="small"
              :percent="item.progress / 100"
              :show-info="false"
            />
            <span class="progress-number"
              >{{ Math.floor(item.progress / 100) }}%</span
            >
          </div>
          <!--导入取消-->
          <div v-else class="progress-container">
            <a-progress
              class="task-progress"
              size="small"
              :percent="item.progress / 100"
              :show-info="false"
            />
            <a-icon-font
              class="icon-status"
              type="iconzengjia-copy"
            ></a-icon-font>
            已取消
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator'
// @ts-ignored
import AProgress from 'ant-design-vue/es/progress/progress'
import DataStore from '@/store/modules/data'
import { Modal } from 'ant-design-vue'

@Component({
  components: {
    AProgress,
  },
})
export default class DataIsUploadedPage extends Vue {
  @Prop() private uploadProgresses: any // = {finalFlag:true, progresses:[{table: 'aaa',progress:12,err:'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111'},{table:'aaab',progress:100,time:123},{table:'aaa',progress:78}]}
  private canceled: boolean = false
  // 鼠标位置
  public isMove = false
  public clientX: number = 0
  public clientY: number = 0
  public modalRight = 22
  public modalTop = 193
  // 窗口状态：展开/收起
  public winOpen = true

  public destroyed() {
    window.removeEventListener('mousedown', this.mousemove)
  }

  // 传输是否完成；若全部成功的话直接跳转；否则停留展示
  private get finished() {
    console.log('finished------------', this.getProgresses)
    let result = true
    if (this.getProgresses.length === 0) {
      return false
    }
    if (this.getProgresses) {
      this.getProgresses.forEach((item: any) => {
        if (item.status === '进行中') {
          result = false
        }
      })
    }
    return result
  }

  public get buttonMarginTop() {
    if (this.uploadProgresses.progresses) {
      return 380 - this.uploadProgresses.progresses.length * 51 < 32
        ? 32
        : 380 - this.uploadProgresses.progresses.length * 51
    }
    return 32
  }

  public get getProgresses() {
    return this.uploadProgresses.progresses
      ? this.uploadProgresses.progresses
      : []
  }

  public get finishedNumber() {
    let count = 0
    if (this.getProgresses) {
      this.getProgresses.forEach((item: any) => {
        if (item.status === '成功') {
          count += 1
        }
      })
    }
    return count
  }

  // 是否有失败任务
  public get isHealthy() {
    let isHealthy = true
    if (this.uploadProgresses.progresses) {
      this.uploadProgresses.progresses.forEach((item: any) => {
        if (item.err) {
          isHealthy = false
        }
      })
    }
    return isHealthy
  }

  // 关闭进度页面
  public closeProgressPage() {
    if (!this.finished) {
      return
    }
    this.$emit('reset-result')
  }

  // 确定按钮
  public click() {
    // 未完成传输，清除状态
    if (!this.uploadProgresses.finalFlag && !this.canceled) {
      DataStore.cancelImport()
      DataStore.setDataIsUploading(true)
      this.$router.push('/management/data')
    }
    // 完成传输或取消之后的跳转
    else {
      DataStore.cancelImport()
      DataStore.setIsUploading(true)
      this.$router.push('/management/data/import')
    }
    this.$emit('reset-result')
  }

  // 取消传输按钮
  public cancel() {
    Modal.confirm({
      title: '确定要取消导入么？',
      content: '取消导入将取消所有未完成的任务',
      okText: '确定',
      cancelText: '取消',
      onOk: this.cancelDatabaseImport,
    })
  }

  public async cancelDatabaseImport() {
    await DataStore.cancelDatabaseImport().then((response) => {
      if (response.data.code === 100) {
        // 正常取消，返回结果
        this.canceled = true
        // 停止轮询
        this.$emit('clear-progresses-interval')
        this.$message.success('未完成任务取消成功')
      } else if (response.data.code === 40010) {
        // 任务实际已经传输成功，提示相应结果
        this.$message.config({ maxCount: 2 })
        this.$message.warn('数据导入已完成，取消失败')
      } else {
        this.$message.error('任务取消失败', response.data.message)
      }
    })
  }

  // 窗口拖动
  public mousedown(event: any) {
    document.addEventListener('mousemove', this.mousemove)
    this.isMove = true
    this.clientX = event.clientX
    this.clientY = event.clientY
  }

  public mousemove(event: any) {
    if (this.isMove) {
      this.modalTop += event.clientY - this.clientY
      this.modalRight += this.clientX - event.clientX
      this.clientY = event.clientY
      this.clientX = event.clientX
    }
  }

  public mouseup() {
    this.isMove = false
  }

  // 点击加载栏中的项目
  public clickTable(id: any) {
    DataStore.setSelectedDatasetId(id)
    this.$emit('set-selected-keys', [`dataset${id}`])
    setTimeout(() => {
      document.querySelectorAll(`#dataset${id}`)[0].scrollIntoView()
    }, 300)
  }
}
</script>

<style lang="less" scoped>
.spin-container {
  height: 65px;
  margin: auto;
  margin-top: 80px;
  width: 65px;
}

.span-container {
  font-size: 16px;
  margin: 32px auto;
  text-align: center;
}

// 标题
.title-container {
  color: #5d637e;
  font-size: 14px;
  font-weight: 500;
  height: 38px;
  letter-spacing: 1px;
  line-height: 20px;
  padding: 9px 24px;
}

// 关闭按钮及其他按钮
.more-icon-container {
  position: absolute;
  right: 16px;
  top: 12px;
}

.more-icon {
  font-size: 13px;
  margin-right: 8px;
  vertical-align: top;
}

// 表名
.table-name {
  display: inline-block;
  overflow: hidden;
  padding-left: 26px;
  text-overflow: ellipsis;
  vertical-align: bottom;
  white-space: nowrap;
  width: 42%;
}

.table-container {
  color: #5d637e;
  overflow-y: auto;

  &::-webkit-scrollbar {
    height: 6px;
    width: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(144, 147, 153, 0.5);
    border-radius: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
    border-radius: 5px;
  }
}

.table-items-container {
  margin-left: 26px;
}

.table-item {
  font-size: 12px;
  height: 32px;
  padding: 7px 0;
}

.icon-container {
  color: #6973ff;
  font-size: 65px;
}

/* 完成/失败的图标 */
.icon-status {
  font-size: 12px;
  margin-left: 9px;
  margin-right: 12px;
  vertical-align: text-bottom;
}

/* 进行中任务的进度数字 */
.progress-number {
  color: #5d637e;
  margin-left: 8px;
}

.progress-container {
  display: inline-block;
}

.task-progress {
  display: inline-block;
  width: 73px;
}

.button-container {
  display: block;
  margin: 32px auto;
  text-align: center;
}

/*.*/
</style>
